package com.example.divesb.config;

import com.example.divesb.http.converter.json.PropertiesHttpMessageConverter;
import com.example.divesb.support.PropertiesHandlerMethodArgumentResolver;
import com.example.divesb.support.PropertiesHandlerMethodReturnValueHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class RestMvcConfigurer implements WebMvcConfigurer {


    @Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @PostConstruct
    public void  init(){
       //初始化 這樣設置優先級為首位
       List<HandlerMethodArgumentResolver> resolvers = requestMappingHandlerAdapter.getArgumentResolvers();
       List<HandlerMethodArgumentResolver> newResolvers = new ArrayList<>(resolvers.size()+1);
       newResolvers.add(new PropertiesHandlerMethodArgumentResolver());
       newResolvers.addAll(resolvers);
       requestMappingHandlerAdapter.setArgumentResolvers(newResolvers);

       List<HandlerMethodReturnValueHandler> handlers = requestMappingHandlerAdapter.getReturnValueHandlers();
       List<HandlerMethodReturnValueHandler> newHandlers = new ArrayList<>(handlers.size()+1);
       newHandlers.add(new PropertiesHandlerMethodReturnValueHandler());
       newHandlers.addAll(handlers);
       requestMappingHandlerAdapter.setReturnValueHandlers(newHandlers);

    }

    public  void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        //优先级低于内置ArgumentResolver
       // resolvers.add(new PropertiesHandlerMethodArgumentResolver());
    }
    public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
        //优先级低于内置ReturnValueHandler
    }

    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        PropertiesHttpMessageConverter propertiesHttpMessageConverter =new PropertiesHttpMessageConverter();
        converters.set(0,propertiesHttpMessageConverter);
    }



}
